package com.fakesmoker.aidawnda.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fakesmoker.aidawnda.common.ErrorCode;
import com.fakesmoker.aidawnda.constant.CommonConstant;
import com.fakesmoker.aidawnda.exception.ThrowUtils;
import com.fakesmoker.aidawnda.mapper.UserTagMapper;
import com.fakesmoker.aidawnda.model.dto.usertag.UserTagQueryRequest;
import com.fakesmoker.aidawnda.model.entity.User;
import com.fakesmoker.aidawnda.model.entity.UserTag;
import com.fakesmoker.aidawnda.model.vo.UserTagVO;
import com.fakesmoker.aidawnda.model.vo.UserVO;
import com.fakesmoker.aidawnda.service.UserTagService;
import com.fakesmoker.aidawnda.service.UserService;
import com.fakesmoker.aidawnda.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户回用户标签表服务实现
 *
 * @author lcy
 */
@Service
@Slf4j
public class UserTagServiceImpl extends ServiceImpl<UserTagMapper, UserTag> implements UserTagService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param userTag
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validUserTag(UserTag userTag, boolean add) {
        ThrowUtils.throwIf(userTag == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String tagName = userTag.getTagName();
        Long id = userTag.getId();

        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(tagName), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(tagName)) {
            ThrowUtils.throwIf(tagName.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }

    }

    /**
     * 获取查询条件
     *
     * @param userTagQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<UserTag> getQueryWrapper(UserTagQueryRequest userTagQueryRequest) {
        QueryWrapper<UserTag> queryWrapper = new QueryWrapper<>();
        if (userTagQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = userTagQueryRequest.getId();
        String searchText = userTagQueryRequest.getSearchText();
        String sortField = userTagQueryRequest.getSortField();
        Long userId = userTagQueryRequest.getUserId();
        int current = userTagQueryRequest.getCurrent();
        int pageSize = userTagQueryRequest.getPageSize();
        String sortOrder = userTagQueryRequest.getSortOrder();

        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("tagName", searchText));
        }

        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取用户回用户标签表封装
     *
     * @param userTag
     * @param request
     * @return
     */
    @Override
    public UserTagVO getUserTagVO(UserTag userTag, HttpServletRequest request) {
        // 对象转封装类
        UserTagVO userTagVO = UserTagVO.objToVo(userTag);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = userTag.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        userTagVO.setUser(userVO);
        // endregion

        return userTagVO;
    }

    /**
     * 分页获取用户回用户标签表封装
     *
     * @param userTagPage
     * @param request
     * @return
     */
    @Override
    public Page<UserTagVO> getUserTagVOPage(Page<UserTag> userTagPage, HttpServletRequest request) {
        List<UserTag> userTagList = userTagPage.getRecords();
        Page<UserTagVO> userTagVOPage = new Page<>(userTagPage.getCurrent(), userTagPage.getSize(), userTagPage.getTotal());
        if (CollUtil.isEmpty(userTagList)) {
            return userTagVOPage;
        }
        // 对象列表 => 封装对象列表
        List<UserTagVO> userTagVOList = userTagList.stream().map(userTag -> {
            return UserTagVO.objToVo(userTag);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = userTagList.stream().map(UserTag::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        userTagVOList.forEach(userTagVO -> {
            Long userId = userTagVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            userTagVO.setUser(userService.getUserVO(user));
        });
        // endregion

        userTagVOPage.setRecords(userTagVOList);
        return userTagVOPage;
    }

}
